    //
//  ItemsViewController.m
//  RssReader
//
//  Created by Wang Shuguang on 12-4-25.
//  Copyright 2012 Dawn. All rights reserved.
//

#import "ItemsViewController.h"
#import "ItemCell.h"
#import "DescriptionViewController.h"

@interface ItemsViewController()
-(void) saveReadStatus;
@end

@implementation ItemsViewController
@synthesize channelIndex;
@synthesize itemsArray;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.view.frame = CGRectMake(0, 20, 320, 460);
	self.view.backgroundColor = [UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:239.0/255.0 alpha:1.0];
    itemsArray = nil;
    itemsNum = ITEM_NUM;
	
	
	
	//向右滑动跳转回上一页
	UISwipeGestureRecognizer *oneFingerSwipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerSwipeRight:)];
	[oneFingerSwipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
	[[self view] addGestureRecognizer:oneFingerSwipeRight];
	[oneFingerSwipeRight release];
	
    itemsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 34, 320, 460-34) style:UITableViewStylePlain];
    itemsTableView.showsVerticalScrollIndicator = YES;
    itemsTableView.showsHorizontalScrollIndicator = NO;
	itemsTableView.rowHeight = 70;
    itemsTableView.delegate = self;
    itemsTableView.dataSource = self;
	itemsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	itemsTableView.backgroundColor = [UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:239.0/255.0 alpha:1.0];
	itemsTableView.sectionFooterHeight = 40;
    
    //更多按钮
    UIView *itemsFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    itemsTableView.tableFooterView = itemsFooterView;
    itemsTableView.tableFooterView.hidden = YES;
    [itemsFooterView release];
    UIButton *moreButton = [PublicMethods buttonWithImage:nil backgroundImage:[UIImage imageNamed:@"more_item.png"] highlightedBackgroundImage:[UIImage imageNamed:@"more_item_heighlight.png"]];
    moreButton.frame = CGRectMake(0, 0, 304, 33);
    moreButton.center = CGPointMake(320/2, 33.0/2 + 4);
    [moreButton setTitle:@"显示更多" forState:UIControlStateNormal];
    [moreButton setTitleColor:[UIColor colorWithRed:100.0f/255.0f green:100.0f/255.0f blue:100.0/255.0f alpha:1] forState:UIControlStateNormal];
    [moreButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [moreButton addTarget:self action:@selector(moreItem:) forControlEvents:UIControlEventTouchUpInside];
    [itemsFooterView addSubview:moreButton];
    
    
	//下拉刷新框
	if (_refreshHeaderView == nil) {
		
		EGORefreshTableHeaderView *egoRefreshView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 
																									  0.0f - itemsTableView.bounds.size.height, 
																									  itemsTableView.bounds.size.width, 
																									  itemsTableView.bounds.size.height)];
		//_reloading = NO;
		egoRefreshView.delegate = self;
		[itemsTableView addSubview:egoRefreshView];
		_refreshHeaderView = egoRefreshView;
		[egoRefreshView release];
		
	}
	[self.view addSubview:itemsTableView];
    [itemsTableView release];
	
	//导航条
	UIImageView *navView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 37)];
	navView.image = [UIImage noCacheImageNamed:@"navbar_background.png"];
	navView.userInteractionEnabled = YES;
	[self.view addSubview:navView];
	//返回按钮
	UIButton *backButton = [PublicMethods buttonWithImage:nil 
										  backgroundImage:[UIImage noCacheImageNamed:@"navbar_back_normal.png"] 
							   highlightedBackgroundImage:[UIImage noCacheImageNamed:@"navbar_back_heighlight.png"]];
	backButton.frame = CGRectMake(0, 0, 47, 35);
	[backButton addTarget:self action:@selector(navBack:) forControlEvents:UIControlEventTouchUpInside];
	[navView addSubview:backButton];
	//频道名
	navTitle = [[UILabel alloc] initWithFrame:CGRectMake(47, 0, 320-47-47, 37)];
	navTitle.font = [UIFont systemFontOfSize:12.0f];
	navTitle.textColor = [UIColor colorWithRed:100.0f/255 green:100.0f/255 blue:100.0f/255 alpha:1];
	navTitle.textAlignment = UITextAlignmentCenter;
	navTitle.backgroundColor = [UIColor clearColor];
	[navView addSubview:navTitle];
	[navTitle release];
	
	Rss *rss = [Rss shareRss];
	NSArray *channels = [rss channels];
	NSDictionary *dict = [channels objectAtIndex:self.channelIndex];
	navTitle.text = [NSString stringWithFormat:@"%@",[dict objectForKey:@"Title"]];
	
    
    UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];			//得到window
    [window startLoading];
    
   
    rss.delegate = self;
	[[Rss shareRss] updateChannel:self.channelIndex];
}

-(void) navBack:(id)sender{
	[self.navigationController popViewControllerAnimated:YES];
    Rss *rss = [Rss shareRss];
    rss.delegate = nil;
    UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];			//得到window
    [window endLoading];
    
    //保存阅读状态
	[self saveReadStatus];
}

-(void) moreItem:(id)sender{
    itemsNum+=20;
    if (itemsNum>[itemsArray count]) {
        itemsNum = [itemsArray count];
        itemsTableView.tableFooterView.hidden = YES;
    }
    [itemsTableView reloadData];
}

-(void) saveReadStatus{
    //保存阅读状态
    Rss *rss = [Rss shareRss];
	NSArray *channels = [rss channels];
	NSDictionary *dict = [channels objectAtIndex:self.channelIndex];
    NSString *dataPath = [NSString stringWithFormat:@"%@.plist",[rss channelPathForKey:[dict objectForKey:@"Url"]]];
	[self.itemsArray writeToFile:dataPath atomically:YES];
}

#pragma mark -
#pragma mark 手势
- (void)oneFingerSwipeRight:(UISwipeGestureRecognizer *)recognizer{ 
	[self performSelector:@selector(navBack:)];
}

#pragma mark -
#pragma mark RssDelegate
-(void) updateDidFinishedWithData:(NSArray *)data withNet:(BOOL)net{
    self.itemsArray = data;
    UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];			//得到window
    [window endLoading];
	if (_reloading) {
		if (net) {
			[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.2];
		}
	}else {
        //更新上次刷新时间
        [_refreshHeaderView refreshLastUpdatedDate];
        [itemsTableView reloadData];
	}
	
	Rss *rss = [Rss shareRss];
	NSArray *channels = [rss channels];
	NSDictionary *dict = [channels objectAtIndex:self.channelIndex];
	navTitle.text = [NSString stringWithFormat:@"%@(%d)",[dict objectForKey:@"Title"],[data count]];
	
    if ([itemsArray count]<=itemsNum) {
        itemsTableView.tableFooterView.hidden = YES;
    }else {
        itemsTableView.tableFooterView.hidden = NO;
    }
}

-(void) updateDidFailed{
	UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];			//得到window
    [window endLoading];
	if (_reloading) {
		[self performSelector:@selector(doneLoadingTableViewData)];
	}
}

-(void) updateingWithProgress:(float)progress{
	UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];			//得到window
    [window setLoadingProgress:progress];
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	[self performSelector:@selector(reloadTableViewDataSource)];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	return _reloading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	Rss *rss = [Rss shareRss];
	NSDictionary *channel = [rss.channels objectAtIndex:self.channelIndex];
	NSDate *lastDate = (NSDate *)[channel objectForKey:@"LastUpdateTime"];
	return lastDate;
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
	
	Rss *rss = [Rss shareRss];
    rss.delegate = self;
	[[Rss shareRss] updateChannelNow:self.channelIndex];
    
    //保存阅读状态
	[self saveReadStatus];
    
    itemsNum = ITEM_NUM;
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[itemsTableView reloadData];
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:itemsTableView];
}

#pragma mark -
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}

#pragma mark -
#pragma mark UITableViewDelegate
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	NSDictionary *item = [self.itemsArray objectAtIndex:indexPath.row];
	DescriptionViewController *descVC = [[DescriptionViewController alloc] init];
	descVC.item = item;
    descVC.channelIndex = self.channelIndex;
	[self.navigationController pushViewController:descVC animated:YES];
	[descVC release];
	
    //取消选中
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	
	//数据标记为已读
	NSDictionary *dict = [itemsArray objectAtIndex:indexPath.row];
	[dict setValue:[NSNumber numberWithBool:YES] forKey:@"flag"];
	
    //cell标记为已读
	ItemCell *cell = (ItemCell *)[tableView cellForRowAtIndexPath:indexPath];
	[cell setReaded:YES];
}

#pragma mark -
#pragma mark UITableViewDataSource
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (itemsArray) {
        return itemsNum;
    }else {
        return 0;
    }
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	return 70;
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ItemCell *cell = (ItemCell *)[tableView dequeueReusableCellWithIdentifier:@"item"];
    if (!cell) {
        cell = [[[ItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"item"] autorelease];
    }
    NSDictionary *dict = [itemsArray objectAtIndex:indexPath.row];
    [cell setTitle:[dict objectForKey:@"title"]];
    NSString *descStr = [PublicMethods flattenHTML: [dict objectForKey:@"description"]];
    if ([descStr length]>50) {
        descStr =  [descStr substringToIndex:50];
    }
	[cell setDesc:descStr];
    
    [cell setPubDate:[dict objectForKey:@"pubdate"]];
	[cell setReaded:[[dict objectForKey:@"flag"] boolValue]];
    return cell;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [itemsArray release];
    [super dealloc];
}


@end
